using System;
using System.Collections.Generic;
using System.Text;
using Decav.Gatsb.Data;

namespace Decav.Gatsb.Application.CommandInterpreters
{
    /// <summary>
    /// Finds information about a place and returns it to the user.
    /// </summary>
    public class FindLocationCommandInterpreter : ICommandInterpreter
    {
        #region ICommandInterpreter Members

        public void Execute(CommandInterpreterContext context)
        {
            if (!context.MessageHasText || context.ResponseEnded)
                return;

            string locationName = null;
            if (!context.FindCommand(_commandPrefixes, out locationName))
                return;

            if (string.IsNullOrEmpty(locationName))
                return;

            Location[] locations = GatsbApplication.Current.FindLocation(new LocationSearchCriteria(locationName, GatsbApplication.Current.CurrentUser.PostalCode));

            if (locations.Length == 0)
            {
                context.SendResponse(string.Format("No location was found for '{0}'.", locationName));
            }
            else if (locations.Length == 1)
            {
                Location location = locations[0];

                StringBuilder builder = new StringBuilder();
                builder.AppendLine(location.Name);
                builder.AppendLine(location.Address.Address1);
                builder.AppendFormat("Tel {0}\r\n",location.TelephoneNumber);
                builder.AppendLine();

                User[] currentUsers = null;
                using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
                    currentUsers = adapt.GetLocationCurrentVisitors(location.Id);

                if (currentUsers.Length > 0)
                    builder.AppendLine("Guests:");

                // Add who is here.
                for (int i = 0; i < currentUsers.Length; i++)
                {
                    string name = currentUsers[i].Name.ToString();
                    string entry = string.Format("-{0}\r\n",  name);

                    if (builder.Length + entry.Length > SetLocationCommandInterpreter.MaxTextMessageLength)
                        break;

                    builder.Append(entry);
                }

                context.SendResponse(builder.ToString());
            }
            else
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("We found:");
                SetLocationCommandInterpreter.CreateLocationList(builder, locations);

                context.SendResponse(builder.ToString());
            }

            context.RemoveFirstBodyLine();
            context.EndResponse();
        }

        private readonly string[] _commandPrefixes = new string[] { "?", "find ", "where is ", "location ", "location of", "place ", "venue " };

        #endregion
    }
}
